package bmatch.tech.file.util;

import bmatch.tech.file.model.MyDirectory;
import bmatch.tech.file.model.MyFile;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class DataStore {

    /**
     * 文件夹缓存
     */
    private static Map<String, List<MyDirectory>> directories;
    /**
     * 文件缓存
     */
    private static Map<String, List<MyFile>> files;

    /**
     * Map映射
     */
    private static ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 模拟数据库的json文件
     */
    private static File directoriesFile = new File("./directories.json");

    /**
     * 模拟数据库的json文件
     */
    private static File filesFile = new File("./files.json");

    /**
     * 初始化缓存
     */
    static {
        directories = new HashMap<>();
        files = new HashMap<>();

        try {
            directories = objectMapper.readValue(directoriesFile, new TypeReference<Map<String, List<MyDirectory>>>() {
            });
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            files = objectMapper.readValue(filesFile, new TypeReference<Map<String, List<MyFile>>>() {
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Map<String, List<MyDirectory>> getDirectories() {
        return directories;
    }

    public static Map<String, List<MyFile>> getFiles() {
        return files;
    }

    /**
     * 保存文件
     */
    public static void storeFiles() {
        if (files == null) {
            return;
        }
        try {
            objectMapper.writeValue(filesFile, files);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存文件夹
     */
    public static void storeDirectories() {
        if (directories == null) {
            return;
        }
        try {
            objectMapper.writeValue(directoriesFile, directories);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
